<template>
  <div>
    <!-- Tab 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="线索" name="clue">
        <!-- 线索管理内容 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>线索管理</span>
          </div>

          <!-- 搜索表单 -->
          <el-form :inline="true" :model="searchForm" class="demo-form-inline">
            <el-form-item label="线索ID：">
              <el-input v-model="searchForm.id" placeholder="请输入线索ID" clearable size="small"></el-input>
            </el-form-item>

            <el-form-item label="手机号：">
              <el-input v-model="searchForm.phone" placeholder="请输入手机号" clearable size="small"></el-input>
            </el-form-item>

            <el-form-item label="线索归属：">
              <el-input v-model="searchForm.owner" placeholder="请输入线索归属" clearable size="small"></el-input>
            </el-form-item>

            <el-form-item label="创建时间：">
              <el-date-picker
                  v-model="dateRange"
                  size="small"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="线索状态：">
              <el-select v-model="searchForm.status" placeholder="请选择线索状态" clearable size="small">
                <el-option
                    v-for="item in statusOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="渠道来源：">
              <el-select v-model="searchForm.channel" placeholder="请选择渠道来源" clearable size="small">
                <el-option
                    v-for="item in channelOptions"
                    :key="item.dictValue"
                    :label="item.dictLabel"
                    :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="doSearch">搜索</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 数据表格卡片 -->
        <el-card class="box-card">
          <el-button type="primary" style="margin-bottom: 10px" @click="handleAdd" v-hasPermi="'system:clue:add'">新建线索
          </el-button>

          <el-table :data="pageData.data" style="width: 100%" border>
            <el-table-column prop="id" label="线索ID" width="80px"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="phone" label="手机号"></el-table-column>
            <el-table-column prop="channel" label="渠道来源" width="120px">
              <template slot-scope="scope">
                {{ getDictLabel(scope.row.channel, channelOptions) }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column prop="owner" label="归属人"></el-table-column>
            <el-table-column prop="status" label="状态" width="100px">
              <template slot-scope="scope">
                {{ getDictLabel(scope.row.status, statusOptions) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="240px">
              <template slot-scope="scope">
                <!-- 线索表格中的查看按钮 -->
                <el-button size="mini" @click="handleView(scope.$index, scope.row)">
                  查看
                </el-button>
                <el-button type="success" size="mini" @click="handleFollowUp(scope.$index, scope.row)">
                  跟进
                </el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">
                  分配
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 -->
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="pageData.pageNo"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="pageData.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pageData.totalCount">
          </el-pagination>

          <!-- 添加/编辑对话框 -->
          <el-dialog title='新增线锁' :visible.sync="dialogFormVisible">
            <el-form :model="saveForm" :rules="rules" ref="saveForm" label-width="90px">
              <!-- 第一行：手机号和渠道来源 -->
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="手机号" prop="phone">
                    <el-input v-model="saveForm.phone" autocomplete="off" maxlength="11"
                              placeholder="请输入手机号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="渠道来源" prop="channel">
                    <el-select v-model="saveForm.channel" placeholder="请输入渠道来源" style="width:100%">
                      <el-option
                          v-for="item in channelOptions"
                          :key="item.dictValue"
                          :label="item.dictLabel"
                          :value="item.dictValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第二行：活动信息和客户姓名 -->
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="活动信息">
                    <el-select v-model="saveForm.activityId" placeholder="请选择活动信息" style="width:100%">
                      <el-option
                          v-for="item in activityOptions"
                          :key="item.id"
                          :label="item.name"
                          :value="item.id">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="客户姓名" prop="name">
                    <el-input v-model="saveForm.name" autocomplete="off" placeholder="请输入客户姓名"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第三行：性别和年龄 -->
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="性别">
                    <el-radio-group v-model="saveForm.sex">
                      <el-radio label="1">男</el-radio>
                      <el-radio label="0">女</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="年龄">
                    <el-input-number v-model="saveForm.age" :min="0" :max="150" placeholder="请输入年龄"
                                     style="width:100%"></el-input-number>
                  </el-form-item>
                </el-col>
              </el-row>

              <!-- 第四行：微信和QQ -->
              <el-row :gutter="30">
                <el-col :span="12">
                  <el-form-item label="微信">
                    <el-input v-model="saveForm.weixin" autocomplete="off" placeholder="请输入微信号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="QQ">
                    <el-input v-model="saveForm.qq" autocomplete="off" placeholder="请输入qq"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisible = false" style="background-color: #f5f5f5; border-color: #dcdfe6;">取
                消
              </el-button>
              <el-button type="primary" @click="doSave" style="background-color: #409eff; border-color: #409eff;">确
                定
              </el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-tab-pane>

      <el-tab-pane label="线索池" name="cluePool">
        <!-- 线索池内容 -->
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>线索池管理</span>
          </div>

          <!-- 搜索表单 - 线索池 -->
          <el-form :inline="true" :model="poolSearchForm" class="demo-form-inline">
            <el-form-item label="线索ID：">
              <el-input v-model="poolSearchForm.id" placeholder="请输入线索ID" clearable size="small"></el-input>
            </el-form-item>

            <el-form-item label="手机号：">
              <el-input v-model="poolSearchForm.phone" placeholder="请输入手机号" clearable size="small"></el-input>
            </el-form-item>

            <el-form-item label="创建时间：">
              <el-date-picker
                  v-model="poolDateRange"
                  size="small"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd">
              </el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="doPoolSearch">搜索</el-button>
              <el-button @click="resetPoolForm">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>

        <!-- 线索池数据表格 -->
        <el-card class="box-card">
          <el-button type="primary" style="margin-bottom: 10px" @click="handlePoolAdd"
                     v-hasPermi="'system:cluePool:add'">新建线索
          </el-button>

          <el-table :data="poolPageData.data" style="width: 100%" border>
            <el-table-column prop="id" label="线索ID" width="80px"></el-table-column>
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="phone" label="手机号"></el-table-column>
            <el-table-column prop="channel" label="渠道来源" width="120px">
              <template slot-scope="scope">
                {{ getDictLabel(scope.row.channel, channelOptions) }}
              </template>
            </el-table-column>
            <el-table-column prop="activityId" label="活动名称" width="120px">
              <template slot-scope="scope">
                {{ getDictLabel(scope.row.activityId, activityOptions) }}
              </template>
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间"></el-table-column>
            <el-table-column label="操作" width="180px">
              <template slot-scope="scope">
                <!-- 线索表格中的查看按钮 -->
                <el-button size="mini" @click="handleView(scope.$index, scope.row)">
                  查看
                </el-button>
                <el-button size="mini" type="danger">
                  捞取
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页组件 - 线索池 -->
          <el-pagination
              @size-change="handlePoolSizeChange"
              @current-change="handlePoolCurrentChange"
              :current-page="poolPageData.pageNo"
              :page-sizes="[5, 10, 15, 20]"
              :page-size="poolPageData.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="poolPageData.totalCount">
          </el-pagination>

          <!-- 添加/编辑对话框 - 线索池 -->
          <el-dialog :title="poolSaveForm.id==null?'新增线索池':'修改线索池'" :visible.sync="poolDialogFormVisible">
            <el-form :model="poolSaveForm" :rules="poolRules" ref="poolSaveForm" label-width="90px">
              <el-form-item label="姓名" prop="name">
                <el-input v-model="poolSaveForm.name" autocomplete="off" placeholder="请输入姓名"></el-input>
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                <el-input v-model="poolSaveForm.phone" autocomplete="off" maxlength="11"
                          placeholder="请输入手机号"></el-input>
              </el-form-item>
              <el-form-item label="来源">
                <el-input v-model="poolSaveForm.source" autocomplete="off" placeholder="请输入来源"></el-input>
              </el-form-item>
              <el-form-item label="备注">
                <el-input type="textarea" v-model="poolSaveForm.remark" autocomplete="off" placeholder="请输入备注"
                          style="width:520px"></el-input>
              </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
              <el-button @click="poolDialogFormVisible = false"
                         style="background-color: #f5f5f5; border-color: #dcdfe6;">取 消
              </el-button>
              <el-button type="primary" @click="doPoolSave" style="background-color: #409eff; border-color: #409eff;">确
                定
              </el-button>
            </div>
          </el-dialog>
        </el-card>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 当前激活的 tab
      activeTab: 'clue',

      // 线索搜索条件
      searchForm: {
        id: null,
        phone: null,
        owner: null,
        beginTime: null,
        endTime: null,
        status: null,
        channel: null,
        pageNo: 1,
        pageSize: 5,
      },

      // 线索池搜索条件
      poolSearchForm: {
        id: null,
        phone: null,
        beginTime: null,
        endTime: null,
        pageNo: 1,
        pageSize: 5,
      },

      // 日期范围
      dateRange: [],
      poolDateRange: [],

      // 字典数据
      statusOptions: [],
      channelOptions: [],

      // 分页数据 - 线索
      pageData: {
        data: [],
        pageNo: 1,
        pageSize: 5,
        totalCount: 0,
        totalPageCount: 0,
      },

      // 分页数据 - 线索池
      poolPageData: {
        data: [],
        pageNo: 1,
        pageSize: 5,
        totalCount: 0,
        totalPageCount: 0,
      },

      // 对话框显示控制 - 线索
      dialogFormVisible: false,
      saveForm: {
        id: null,
        name: null,
        phone: null,
        channel: '0',
        owner: null,
        activityId: null,
        sex: '1',
        age: null,
        weixin: null,
        qq: null,
      },

      // 对话框显示控制 - 线索池
      poolDialogFormVisible: false,
      poolSaveForm: {
        id: null,
        name: null,
        phone: null,
        source: null,
        remark: null,
      },

      // 表单验证规则 - 线索
      rules: {
        name: [
          {required: true, message: "请输入姓名！", trigger: "blur"},
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            required: true,
            trigger: 'blur'
          }
        ],
        activityId: [
          {required: true, message: "请选择活动信息！", trigger: "change"}
        ]
      },

      // 表单验证规则 - 线索池
      poolRules: {
        name: [
          {required: true, message: "请输入姓名！", trigger: "blur"},
        ],
        phone: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            required: true,
            trigger: 'blur'
          }
        ]
      },

      // 活动信息选项
      activityOptions: [],
    };
  },

  created() {
    this.doSearch();
    this.getDictData();
    this.getDictDataChannel();
    this.getActivityList(); // 获取活动列表

    // 初始化线索池数据
    this.doPoolSearch();
  },

  methods: {
    // 查看线索详情
    handleView(index, row) {
      // 跳转到线索详情页面
      this.$router.push({
        path: '/clue/clueData',
        query: {
          id: row.id
        }
      });
    },
    // 获取活动列表
    getActivityList() {
      this.$axios.get("/api/tb/activity/listAll")
          .then((res) => {
            if (res.data.code == 200) {
              this.activityOptions = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },

    // 获取状态字典数据
    getDictData() {
      this.$axios.get("/api/sys/dict/getDictData?dictType=" + 'clue_status')
          .then((res) => {
            if (res.data.code == 200) {
              this.statusOptions = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },

    // 获取渠道来源字典数据
    getDictDataChannel() {
      this.$axios.get("/api/sys/dict/getDictData?dictType=" + 'channel_source')
          .then((res) => {
            if (res.data.code == 200) {
              this.channelOptions = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },

    // 执行搜索 - 线索
    doSearch() {
      // 设置时间范围
      if (this.dateRange) {
        this.searchForm.beginTime = this.dateRange[0];
        this.searchForm.endTime = this.dateRange[1];
      } else {
        this.searchForm.beginTime = null;
        this.searchForm.endTime = null;
      }

      this.$axios.get("/api/clue/list", {params: this.searchForm})
          .then((res) => {
            if (res.data.code == 200) {
              this.pageData.pageNo = res.data.data.current;
              this.pageData.pageSize = res.data.data.size;
              this.pageData.totalCount = res.data.data.total;
              this.pageData.totalPageCount = res.data.data.pages;
              this.pageData.data = res.data.data.records;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },

    // 重置表单 - 线索
    resetForm() {
      this.searchForm = {
        id: null,
        phone: null,
        owner: null,
        beginTime: null,
        endTime: null,
        status: null,
        channel: null,
        pageNo: 1,
        pageSize: 5,
      };
      this.dateRange = [];
      this.doSearch();
    },

    // 改变每页显示条数 - 线索
    handleSizeChange(val) {
      this.searchForm.pageSize = val;
      this.doSearch();
    },

    // 改变当前页码 - 线索
    handleCurrentChange(val) {
      this.searchForm.pageNo = val;
      this.doSearch();
    },

    // 添加新线索
    handleAdd() {
      this.resetSaveForm();
      this.dialogFormVisible = true;
    },

    // 编辑线索
    handleEdit(index, row) {
      this.$axios.get("/api/clue/view/" + row.id)
          .then((res) => {
            if (res.data.code == 200) {
              this.saveForm = res.data.data;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
      this.dialogFormVisible = true;
    },


    // 跟进线索
    handleFollowUp(index, row) {
      this.$message.info("跟进功能暂未实现");
    },

    // 保存线索
    doSave() {
      this.$refs["saveForm"].validate((valid) => {
        if (valid) {
          this.$axios.post("/api/clue", this.saveForm)
              .then((res) => {
                if (res.data.code == 200) {
                  this.dialogFormVisible = false;
                  this.$message.success(res.data.msg);
                  this.doSearch();
                } else {
                  this.$message.error(res.data.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
        }
      });
    },

    // 重置保存表单 - 线索
    resetSaveForm() {
      this.saveForm = {
        id: null,
        name: null,
        phone: null,
        channel: '0',
        owner: null,
        activityId: null,
        sex: '1',
        age: null,
        weixin: null,
        qq: null,
      };
    },

    // 执行搜索 - 线索池
    doPoolSearch() {
      // 设置时间范围
      if (this.poolDateRange) {
        this.poolSearchForm.beginTime = this.poolDateRange[0];
        this.poolSearchForm.endTime = this.poolDateRange[1];
      } else {
        this.poolSearchForm.beginTime = null;
        this.poolSearchForm.endTime = null;
      }

      this.$axios.get("/api/clue/pool", {params: this.poolSearchForm}) // 使用 /api/clue/pool 接口
          .then((res) => {
            if (res.data.code == 200) {
              this.poolPageData.pageNo = res.data.data.current;
              this.poolPageData.pageSize = res.data.data.size;
              this.poolPageData.totalCount = res.data.data.total;
              this.poolPageData.totalPageCount = res.data.data.pages;
              this.poolPageData.data = res.data.data.records;
            } else {
              this.$message.error(res.data.msg);
            }
          })
          .catch((err) => {
            console.log(err);
          });
    },

    // 重置表单 - 线索池
    resetPoolForm() {
      this.poolSearchForm = {
        id: null,
        phone: null,
        beginTime: null,
        endTime: null,
        pageNo: 1,
        pageSize: 5,
      };
      this.poolDateRange = [];
      this.doPoolSearch();
    },

    // 改变每页显示条数 - 线索池
    handlePoolSizeChange(val) {
      this.poolSearchForm.pageSize = val;
      this.doPoolSearch();
    },

    // 改变当前页码 - 线索池
    handlePoolCurrentChange(val) {
      this.poolSearchForm.pageNo = val;
      this.doPoolSearch();
    },

    // 添加新线索池
    handlePoolAdd() {
      this.resetPoolSaveForm();
      this.poolDialogFormVisible = true;
    },




    // 保存线索池
    doPoolSave() {
      this.$refs["poolSaveForm"].validate((valid) => {
        if (valid) {
          const url = this.poolSaveForm.id ? "/api/clue/pool/update" : "/api/clue/pool/save";
          this.$axios.post(url, this.poolSaveForm)
              .then((res) => {
                if (res.data.code == 200) {
                  this.poolDialogFormVisible = false;
                  this.$message.success(res.data.msg);
                  this.doPoolSearch();
                } else {
                  this.$message.error(res.data.msg);
                }
              })
              .catch((err) => {
                console.log(err);
              });
        }
      });
    },

    // 重置保存表单 - 线索池
    resetPoolSaveForm() {
      this.poolSaveForm = {
        id: null,
        name: null,
        phone: null,
        source: null,
        remark: null,
      };
    },

    // Tab 切换事件
    handleTabClick(tab) {
      if (tab.name === 'cluePool') {
        // 切换到线索池时加载数据
        this.doPoolSearch();
      }
    },

    getDictLabel(value, options) {
      if (!value || !options || options.length === 0) {
        return '';
      }
      const dict = options.find(item => item.dictValue === value || item.id === value);
      return dict ? (dict.dictLabel || dict.name) : value;
    },
  }
};
</script>

<style scoped>
.box-card {
  margin-bottom: 20px;
}

.demo-form-inline {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

/* 自定义对话框样式 */
.dialog-footer {
  text-align: right;
  padding-top: 30px;
  padding-bottom: 20px;
}

.dialog-footer .el-button {
  padding: 12px 24px;
  font-size: 14px;
  border-radius: 8px;
  margin-right: 10px;
}

.dialog-footer .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  color: white;
}

.dialog-footer .el-button--default {
  background-color: #f5f5f5;
  border-color: #dcdfe6;
  color: #606266;
}

</style>
